import axios from "axios";
import NProgress from "nprogress"; // 进度条插件
import "nprogress/nprogress.css";

// 创建一个axios的实例
const instance = axios.create({
  baseURL: "http://api.cat-shop.penkuoer.com", // 设置网络请求的基地址
  timeout: 5000,
});

// 全局拦截
// 全局请求拦截,所有的请求发起之前做
// Add a request interceptor
instance.interceptors.request.use(
  function(config) {
    NProgress.start();
    // Do something before request is sent
    config.headers.token = "998"; // 可以加一个自定义的属性
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 全局相应拦截,所有的请求完成之后执行
// Add a response interceptor
instance.interceptors.response.use(
  function(response) {
    NProgress.done();
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response.data;
  },
  function(error) {
    // console.dir(error);
    NProgress.done();
    if (error.response && error.response.status == 401) {
      // window.location.href = '登录页'
    }
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

// export function get(url, params) {
//   return instance.get(url, {
//     params,
//   });
// }

export const get = (url, params) => instance.get(url, { params });

// export function post(url, data) {
//   return instance.post(url, data);
// }

export const post = (url, data) => instance.post(url, data);

export function del(url) {
  return instance.delete(url);
}

export function put(url, data) {
  return instance.put(url, data);
}
